from functools import wraps
from time import sleep


def retry(count=2, try_time=0,error_type=Exception):
    """重试机制"""

    def actual_decorator(function):
        @wraps(function)
        def wrapper_function(*args, **kwargs):
            error = None
            for i in range(count):
                try:
                    return function(*args, **kwargs)
                except error_type as e:
                    error = str(e)
                    if try_time and count - 1 != i: sleep(try_time)
                    continue
            raise ValueError(error)

        return wrapper_function

    return actual_decorator


def compare_lists(old_list:list[dict], new_list:list[dict],lookup_field='id')->dict:
    """对比2个列表字典的差异:新增,修改,删除"""
    old_dict = {item[lookup_field]: item for item in old_list}
    new_dict = {item[lookup_field]: item for item in new_list}
    create = [new_dict[key] for key in new_dict if key not in old_dict]
    update = [new_dict[key] for key in new_dict if key in old_dict and new_dict[key] != old_dict[key]]
    destroy = [old_dict[key] for key in old_dict if key not in new_dict]
    return {'create': create, 'update': update, 'destroy': destroy}

